package com.cjx.stars.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.cjx.stars.common.MyException;
import com.cjx.stars.common.Response;
import com.cjx.stars.common.ResponseUtils;
import com.cjx.stars.pojo.table.User;
import com.cjx.stars.pojo.vo.UserVo;
import com.cjx.stars.service.UserService;
import com.cjx.stars.utils.FileUtils;
import com.cjx.stars.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;

import static com.cjx.stars.constant.FailMessage.FAILED_UPLOAD_AVATAR;
import static com.cjx.stars.constant.FailMessage.FILE_DATA_IS_EMPTY;
import static com.cjx.stars.constant.RedisConstant.USER_LOGIN_KEY;
import static com.cjx.stars.constant.RedisConstant.USER_LOGIN_TTL;

/**
 * @author cjx
 * @description 公共请求
 * @createDate  2024/4/2 20:41
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${stars.qiniu.url:null}")
    private String qiniuUrl;

    @PostMapping("/upload")
    public Response<?> uploadFile(MultipartFile file,HttpServletRequest request) {
        if (file == null) {
            throw new MyException(FILE_DATA_IS_EMPTY);
        }
        String filename = FileUtils.uploadFile(file);
        String fileUrl = qiniuUrl + filename;
        UserVo loginUser = UserHolder.getUser();
        String userId = loginUser.getUserId();
        User user = new User();
        user.setUserId(Long.valueOf(userId));
        user.setAvatarUrl(fileUrl);
        boolean success = userService.updateById(user);

        // 1.获取请求头中的token
        String token = request.getHeader("authorization");
        // 2.更新redis中的用户数据
        User newUser = userService.getById(user.getUserId());
        UserVo newUserVo = BeanUtil.copyProperties(newUser, UserVo.class);
        String jsonStr = JSONUtil.toJsonStr(newUserVo);
        String key  = USER_LOGIN_KEY + token;
        stringRedisTemplate.opsForValue().set(key,jsonStr,USER_LOGIN_TTL, TimeUnit.MINUTES);
        if (!success) {
            throw new MyException(FAILED_UPLOAD_AVATAR);
        }
        return ResponseUtils.success(fileUrl);
    }



}
